package jsu.yym.tiktok.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import jsu.yym.tiktok.mapper.Type;
import jsu.yym.tiktok.mapper.UserMapper;
import jsu.yym.tiktok.pojo.ResponseResult;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.server.QiniuMediaUtilService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VideoService videoService;
    @Resource
    private QiniuMediaUtilService qiniuMediaUtilService;
    //上传头像
    public User uploadImage(MultipartFile file,String id) throws QiniuException {

        System.out.println(id);
        User user = qiniuMediaUtilService.uploadFile(file);
        System.out.println(user.getImage()+"开始审核");
        //审核图片
        try {
            String s = qiniuMediaUtilService.ImageCensor("http://oayjpradp.bkt.clouddn.com/Audrey_Hepburn.jpg");
//            String s1 = resourcesCensor.ImageCensor();
//            System.out.println(resourcesCensor.getVideoCensorResultByJobID(s));
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(s);

            // 提取"suggestion"的值
            String suggestionValue = jsonNode.path("result").path("suggestion").asText();
            System.out.println(suggestionValue);
//            System.out.println(s1);
            String type = videoService.check(suggestionValue);
            if(type.equals(Type.BLOCK))
            {
                //审核不通过，删除上传的图片
                if(qiniuMediaUtilService.delete(user.getFileName()))
                    return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user.getImage());
        //从数据库中获取原来的头像的文件名
        String fileName = userMapper.getFileNameByUserName(id);
        System.out.println(fileName+"kk");
        //从七牛云中删除原来的文件
        if(!qiniuMediaUtilService.delete(fileName)){
            return null;
        }
        return user;
    }

    public void savaUserToEs(User user){
        RestHighLevelClient elasticsearchClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        try {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest("user"); // 替换为你的索引名称
            indexRequest.id(String.valueOf(user.getUsername())); // 使用 User 对象的 Username 作为文档 ID
            String json = userToJson(user); // 将 User 对象转为 JSON 字符串
            indexRequest.source(json, XContentType.JSON);

            // 执行索引请求
            elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

    public void updateUserInElasticsearch(User user) {
        RestHighLevelClient elasticsearchClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        try {
            // 创建更新请求
            UpdateRequest updateRequest = new UpdateRequest("user", user.getUsername());
            String userJson = userToJson(user);

            // 设置更新内容
            updateRequest.doc(userJson, XContentType.JSON);

            // 执行更新请求
            elasticsearchClient.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        } finally {
            try {
                elasticsearchClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String userToJson(User user) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    public void test(){
        List<User> users = userMapper.selectList(null);
        for (User u:users) {
            savaUserToEs(u);
        }
    }

}
